package com.atelier.plugin.service.impl;

import com.atelier.plugin.database.domain.DataBaseConnectionSettingDto;
import com.atelier.plugin.database.domain.DatabaseConnectionInfo;
import com.atelier.plugin.database.listener.ConnectionListChangeListener;
import com.atelier.plugin.database.ui.DataSourceSettingDialog;
import com.atelier.plugin.database.util.PasswordStorageUtil;
import com.atelier.plugin.service.DataBaseConnectionStorageService;
import com.atelier.plugin.tool.ProjectUtils;
import com.intellij.openapi.components.*;
import lombok.Data;
import net.sf.cglib.beans.BeanCopier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@State(
        name = "DataBaseConnection",
        storages = @Storage("DataBaseConnection.xml")
)
@Data
public class DataBaseConnectionStorageServiceImpl implements DataBaseConnectionStorageService {
    public static Logger LOGGER=  LoggerFactory.getLogger(DataBaseConnectionStorageServiceImpl.class);
    private DataBaseConnectionSettingDto dataBaseConnectionSettingDto = new DataBaseConnectionSettingDto();
    private List<ConnectionListChangeListener> listeners = new CopyOnWriteArrayList<>();

    private static final String NO_STATE_LOADED_LOG = "方法在没有状态加载时清空连接信息列表 addConnectionInfo";

    @Nullable
    @Override
    public DataBaseConnectionSettingDto getState() {


        return dataBaseConnectionSettingDto;


    }

    @Override
    public void loadState(@NotNull DataBaseConnectionSettingDto state) {
        dataBaseConnectionSettingDto = state;
        //获取密码
        for (DatabaseConnectionInfo databaseConnectionInfo : dataBaseConnectionSettingDto.getDatabaseConnectionInfos()) {
            databaseConnectionInfo.
                    setPassword(PasswordStorageUtil.getPassword(databaseConnectionInfo.getUuid()));
            LOGGER.info("加载对象名称 "+databaseConnectionInfo.getName()
                    +"加载对象uuid"+databaseConnectionInfo.getUuid()
                    +"加载对象密码"+databaseConnectionInfo.getPassword()
            );
        }
        // 通知监听器，状态已加载
        notifyListeners();
    }

    @Override
    public void noStateLoaded() {
        dataBaseConnectionSettingDto = new DataBaseConnectionSettingDto();
        // 日志记录
        log(NO_STATE_LOADED_LOG);
    }

    @Override
    public void addConnectionListChangeListener(ConnectionListChangeListener listener) {
        listeners.add(listener);
    }

    @Override
    public void removeConnectionListChangeListener(ConnectionListChangeListener listener) {
        listeners.remove(listener);
    }

    public List<DatabaseConnectionInfo> getConnectionInfos() {
        return dataBaseConnectionSettingDto.getDatabaseConnectionInfos();
    }

    public void addConnectionInfo(DatabaseConnectionInfo connectionInfo) {
        dataBaseConnectionSettingDto.getDatabaseConnectionInfos().add(connectionInfo);
        notifyListeners();
    }

    public void removeConnectionInfo(DatabaseConnectionInfo connectionInfo) {
        dataBaseConnectionSettingDto.getDatabaseConnectionInfos().remove(connectionInfo);
        notifyListeners();
    }

    public void removeConnectionInfos(List<DatabaseConnectionInfo> connectionInfoList) {
        dataBaseConnectionSettingDto.getDatabaseConnectionInfos().removeAll(connectionInfoList);
        notifyListeners();
    }

    @Override
    public void clearConnectionInfos() {
        dataBaseConnectionSettingDto.getDatabaseConnectionInfos().clear();
        notifyListeners();
    }

    @Override
    public void mergeAndClearConnectionInfos(List<DatabaseConnectionInfo> newConnectionInfoList) {
        List<DatabaseConnectionInfo> databaseConnectionInfos = dataBaseConnectionSettingDto.getDatabaseConnectionInfos();
        for (DatabaseConnectionInfo databaseConnectionInfo : databaseConnectionInfos) {
            LOGGER.info("删除："+databaseConnectionInfo.getUuid()+"密码："+databaseConnectionInfo.getPassword());
            PasswordStorageUtil.deletePassword(databaseConnectionInfo.getUuid());
        }
        databaseConnectionInfos.clear();
        //密码清除
        for (DatabaseConnectionInfo databaseConnectionInfo : newConnectionInfoList) {
            LOGGER.info("存储："+databaseConnectionInfo.getUuid()+"密码："+databaseConnectionInfo.getPassword());
            PasswordStorageUtil.storePassword(databaseConnectionInfo.getUuid(),databaseConnectionInfo.getPassword());
        }
        dataBaseConnectionSettingDto.getDatabaseConnectionInfos()
                .addAll(newConnectionInfoList);
        //存储密码

        notifyListeners();
    }

    public boolean hasConnectionInfo(DatabaseConnectionInfo connectionInfo) {
        return dataBaseConnectionSettingDto.getDatabaseConnectionInfos().contains(connectionInfo);
    }

    private void notifyListeners() {
        for (ConnectionListChangeListener listener : listeners) {
            listener.connectionListChanged(dataBaseConnectionSettingDto.getDatabaseConnectionInfos());
        }
    }

    // 日志记录方法
    private void log(String message) {
        // 使用合适的日志记录框架来记录日志
        LoggerFactory.getLogger(DataBaseConnectionStorageServiceImpl.class).info(message);
    }

}
